package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Category;
import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
//展示一个大类
/*
* 1、获取用户点击的是哪个大类，得到这个大类的id，通过servlet来得到
* 2、获取含大类中每个小类的列表
*  */
public class ViewCategoryServlet extends HttpServlet {

    private static final String VIEW_CATEGORY = "/WEB-INF/jsp/catalog/Category.jsp";
    private String categoryId;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //点击图片跳转页面时确定用户点的哪个东西，通过请求servlet时把参数带过来，
        //找业务逻辑创建service，调用之中的方法，完成功能

        //获取用户点击的图片或者标签的东西的id
        categoryId = request.getParameter("categoryId");
        //利用业务逻辑层获得所需东西
        CatalogService catalogService = new CatalogService();
        //给你id，把大类
        Category category = catalogService.getCategory(categoryId);
        //通过大类找product列表
        List<Product> productList = catalogService.getProductListByCategory(categoryId);

        //把获得的数据放到作用域里存起来
        HttpSession session = request.getSession();
        session.setAttribute("category",category);
        session.setAttribute("productList",productList);

        Account account = (Account) session.getAttribute("account");
        //时间
        SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datetime = tempDate.format(new java.util.Date());
        //信息
        String info = "查看"+categoryId+"界面";

        if(account != null){
            Log log = new Log(account.getUsername(),datetime,info);
            //添加log
            new AccountService().addLog(log);
        }


        request.getRequestDispatcher(VIEW_CATEGORY).forward(request,response);
    }
}
